package com.xjzd.std.concurrency;

public class AlternatePrintingWithVolatile {
    private static volatile boolean flag = true;
    private static int number = 1;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            for (int i = 1; i <= 50; i++) {
                while (!flag) {
                    // 忙等待
                }
                System.out.println("Thread 1: " + number++);
                flag = false;
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 1; i <= 50; i++) {
                while (flag) {
                    // 忙等待
                }
                System.out.println("Thread 2: " + number++);
                flag = true;
            }
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}